#!/usr/bin/perl

# Script to illustrate how to parse a simple XML file
# and dump its contents in a Perl hash record.

use strict;
use warnings;
use diagnostics;
use XML::LibXML;
use Data::Dumper;
use Getopt::Std;

my %options;

getopts("i:o:", \%options);
 
# test for the existence of the options on the command line.
# in a normal program you'd do more than just print these.
# print "-i $options{i}\n" if defined $options{i};
# print "-o $options{o}\n" if defined $options{o};
print "
Usage:   -i sourcefile.xml -o output.xml


" and exit if not defined $options{o} or not defined $options{i};
 

my $doc = XML::LibXML->createDocument( "1.0", "UTF-8" );
my $root = $doc->createElementNS( "", "FCVocaPhraseList" );
$doc->setDocumentElement( $root );

my $attr;
$attr = $doc->createAttribute( "xmlns:xsi", "http://www.w3.org/2001/XMLSchema" );
$root->setAttributeNodeNS( $attr );
$attr = $doc->createAttribute( "xmlns:xsd", "http://www.w3.org/2001/XMLSchema-instance" );
$root->setAttributeNodeNS( $attr );

my $Phrases = XML::LibXML::Element->new( "Phrases" );
$root->addChild($Phrases);
my $Phrase;

# load
open my $fh, '<', $options{i};
binmode $fh; # drop all PerlIO layers possibly created by a use open pragma
my $doc_in = XML::LibXML->load_xml(IO => $fh);
foreach my $wordbook ($doc_in->childNodes()){
    foreach my $item ($wordbook->childNodes()){

		my $word = $item->find("word");
		my $trans = $item->find("trans");
		my $phonetic = $item->find("phonetic");

		$Phrase = XML::LibXML::Element->new( "Phrase" );
		$Phrase->appendTextChild("Eng", $word);
		$Phrase->appendTextChild("Phonetic", $phonetic);
		$Phrase->appendTextChild("Defi", $trans);
		$Phrase->appendTextChild("Date", "2016-01-12 22:00:00");

		$Phrases->addChild($Phrase);
	}
}
# save
open my $out, '>', $options{o};
binmode $out; # as above
$doc->toFH($out);